<template>
  <div class="page-container">
    <div class="page-header">
      <h2>添加健康数据</h2>
      <p>记录您的身体健康指标</p>
    </div>
    
    <el-card class="form-card">
      <el-form 
        ref="formRef" 
        :model="healthDataForm" 
        :rules="rules" 
        label-width="100px"
        class="health-data-form"
      >
        <el-form-item label="记录日期" prop="recordDate">
          <el-date-picker
            v-model="healthDataForm.recordDate"
            type="datetime"
            placeholder="选择日期和时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 0, 1, 8, 0, 0)"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="身高" prop="height">
          <el-input-number
            v-model="healthDataForm.height"
            :min="50"
            :max="250"
            :precision="1"
            :step="0.5"
            style="width: 100%"
          >
            <template #suffix>厘米 (cm)</template>
          </el-input-number>
        </el-form-item>
        
        <el-form-item label="体重" prop="weight">
          <el-input-number
            v-model="healthDataForm.weight"
            :min="20"
            :max="300"
            :precision="1"
            :step="0.1"
            style="width: 100%"
          >
            <template #suffix>千克 (kg)</template>
          </el-input-number>
        </el-form-item>
        
        <el-form-item label="静息心率" prop="restingHeartRate">
          <el-input-number
            v-model="healthDataForm.restingHeartRate"
            :min="30"
            :max="200"
            :step="1"
            style="width: 100%"
          >
            <template #suffix>次/分钟 (bpm)</template>
          </el-input-number>
        </el-form-item>
        
        <el-form-item v-if="showBmi">
          <el-alert
            :title="`体重指数(BMI): ${calculatedBmi} (${getBmiCategory(calculatedBmi)})`"
            :type="getBmiAlertType(calculatedBmi)"
            :description="getBmiDescription(calculatedBmi)"
            show-icon
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>BMI指数说明</span>
        </div>
      </template>
      <div class="info-content">
        <p>体重指数（Body Mass Index，简称BMI）是用体重公斤数除以身高米数平方得出的数字，是目前国际上常用的衡量人体胖瘦程度以及是否健康的一个标准。</p>
        <div class="bmi-table">
          <div class="bmi-row header">
            <div class="bmi-cell">BMI值</div>
            <div class="bmi-cell">分类</div>
            <div class="bmi-cell">健康风险</div>
          </div>
          <div class="bmi-row">
            <div class="bmi-cell">&lt; 18.5</div>
            <div class="bmi-cell">偏瘦</div>
            <div class="bmi-cell">低（但其他健康问题风险增加）</div>
          </div>
          <div class="bmi-row">
            <div class="bmi-cell">18.5 - 23.9</div>
            <div class="bmi-cell">正常</div>
            <div class="bmi-cell">平均水平</div>
          </div>
          <div class="bmi-row">
            <div class="bmi-cell">24.0 - 27.9</div>
            <div class="bmi-cell">超重</div>
            <div class="bmi-cell">增加</div>
          </div>
          <div class="bmi-row">
            <div class="bmi-cell">≥ 28.0</div>
            <div class="bmi-cell">肥胖</div>
            <div class="bmi-cell">高</div>
          </div>
        </div>
        <p class="note">注：以上标准参考中国成人体重判定标准。BMI只是衡量健康的指标之一，不能完全代表个人的健康状况。</p>
      </div>
    </el-card>
  </div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createHealthData } from '@/api/healthData'

const router = useRouter()
const formRef = ref(null)
const loading = ref(false)
const formatDateToYMDHMS = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
// 表单数据（注意这里recordDate用Date对象！）
const healthDataForm = ref({
  recordDate:formatDateToYMDHMS(new Date()), // 默认当前本地时间
  height: null,
  weight: null,
  restingHeartRate: null
})

// 表单验证规则
const rules = {
  recordDate: [
    { required: true, message: '请选择记录日期', trigger: 'change' }
  ],
  height: [
    { required: true, message: '请输入身高', trigger: 'blur' },
    { type: 'number', min: 50, max: 250, message: '身高范围在50-250厘米之间', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入体重', trigger: 'blur' },
    { type: 'number', min: 20, max: 300, message: '体重范围在20-300千克之间', trigger: 'blur' }
  ],
  restingHeartRate: [
    { type: 'number', min: 30, max: 200, message: '静息心率范围在30-200次/分钟之间', trigger: 'blur' }
  ]
}

// 计算BMI值
const calculatedBmi = computed(() => {
  if (!healthDataForm.value.height || !healthDataForm.value.weight) return null
  const heightInMeters = healthDataForm.value.height / 100
  const bmi = healthDataForm.value.weight / (heightInMeters * heightInMeters)
  return Math.round(bmi * 10) / 10
})

// 是否显示BMI信息
const showBmi = computed(() => {
  return calculatedBmi.value !== null
})

// 获取BMI分类
const getBmiCategory = (bmi) => {
  if (!bmi) return '未知'
  if (bmi < 18.5) {
    return '偏瘦'
  } else if (bmi < 24.0) {
    return '正常'
  } else if (bmi < 28.0) {
    return '超重'
  } else if (bmi < 30.0) {
    return '轻度肥胖'
  } else if (bmi < 40.0) {
    return '中度肥胖'
  } else {
    return '重度肥胖'
  }
}

// 获取BMI提示类型
const getBmiAlertType = (bmi) => {
  if (!bmi) return 'info'
  if (bmi < 18.5) {
    return 'warning'
  } else if (bmi < 24.0) {
    return 'success'
  } else if (bmi < 28.0) {
    return 'warning'
  } else {
    return 'error'
  }
}

// 获取BMI描述
const getBmiDescription = (bmi) => {
  if (!bmi) return ''
  if (bmi < 18.5) {
    return '体重过轻，可能缺乏营养，建议适当增加饮食摄入并进行适度锻炼。'
  } else if (bmi < 24.0) {
    return '体重正常，继续保持健康的生活方式。'
  } else if (bmi < 28.0) {
    return '体重超标，建议控制饮食并增加有氧运动。'
  } else if (bmi < 30.0) {
    return '轻度肥胖，建议调整饮食结构并规律运动。'
  } else if (bmi < 40.0) {
    return '中度肥胖，建议咨询医生并制定减肥计划。'
  } else {
    return '重度肥胖，有较高健康风险，建议在医生指导下进行减重。'
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 确保日期格式为 yyyy-MM-dd HH:mm:ss
    let formattedDate = healthDataForm.value.recordDate

    // 如果是Date对象，则格式化
    if (formattedDate instanceof Date) {
      const date = formattedDate
      formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    }
    // 如果是ISO格式字符串，则转换
    else if (typeof formattedDate === 'string' && formattedDate.includes('T')) {
      formattedDate = formattedDate.replace('T', ' ').substring(0, 19)
    }

    const submitData = {
      ...healthDataForm.value,
      recordDate: formattedDate
    }

    // 添加更多日志输出
    console.log('提交的健康数据:', submitData);
    console.log('日期类型:', typeof submitData.recordDate, '日期值:', submitData.recordDate);

    const response = await createHealthData(submitData)
    console.log('服务器响应:', response);

    ElMessage.success('健康数据添加成功')
    router.push('/health-data')
  } catch (error) {
    console.error('提交健康数据失败:', error)
    ElMessage.error('提交健康数据失败')
  }
}

// 返回列表页
const goBack = () => {
  router.push('/health-data')
}

onMounted(() => {
  // 可以在这里添加初始化逻辑
})
</script>
<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.form-card {
  margin-bottom: 20px;
}

.health-data-form {
  max-width: 600px;
  margin: 0 auto;
}

.info-card {
  margin-bottom: 20px;
}

.info-content {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.bmi-table {
  margin: 20px 0;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.bmi-row {
  display: flex;
  border-bottom: 1px solid #ebeef5;
}

.bmi-row:last-child {
  border-bottom: none;
}

.bmi-row.header {
  background-color: #f5f7fa;
  font-weight: bold;
  color: #303133;
}

.bmi-cell {
  flex: 1;
  padding: 12px 15px;
  border-right: 1px solid #ebeef5;
}

.bmi-cell:last-child {
  border-right: none;
  flex: 2;
}

.note {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

@media (max-width: 768px) {
  .bmi-row {
    flex-direction: column;
  }
  
  .bmi-cell {
    border-right: none;
    border-bottom: 1px solid #ebeef5;
  }
  
  .bmi-cell:last-child {
    border-bottom: none;
  }
}
</style> 